import {
  saveGoodToCart
} from "../../service/jb_shopcar_service"
const app = getApp();
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    goodsData: {
      type: Object,
      value: []
    },
    skuList: {
      type: Array,
      value: []
    },
    productInfo: {
      type: Object,
      value: {
        image: "",
        storeName: "",
      }
    },
    goodType: {
      type: String,
      value: "normal"
    },
    skuObj: {
      type: Object,
      value: {
        image: "",
        price: 0,
        otPrice: 0,
        productId: 0,
        sales: 0,
        suk: ''
      }
    }
  },
  observers: {
    'show': function (value) {
      this.setData({
        showPop: value
      })
    },
    //这里进来不一定是取第一个哦，应该通过点击进来的套餐是啥来决定哦。
    'skuObj': function (value) {
      this.setData({
        selectSkuObj: value
      })
      console.log("JJLog:这里会走嘛+========")
      if (this.properties.goodsData && this.properties.goodsData.length > 0) {
        this.dealCurrentSelectSku(value);
      }

    },
    'productInfo': function (value) {
      console.log("JJLog:商品详情来了：" + JSON.stringify(value));
      if (value && value.minBuyNum) {
        this.setData({
          selectNumber: value.minBuyNum || 1,
        })
      }
    },
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
      // console.log("JJLog:之类来==：" + this.properties.show)
      // this.setData({
      //   showPop: this.properties.show
      // })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    showPop: false,
    initData: {},
    selectSkuObj: {}, //当前选中的sku
    selectNumber: 1, //当前选中商品数量
    selectSkuIndex: 0, //当前选中的sku下标
    overlayStyle: 'background-color: rgba(0, 0, 0, 0.25);',
    sukList: [],//规整好的那个

  },

  /**
   * 组件的方法列表
   */
  methods: {
    closePageContainer() {
      this.setData({
        showPop: false,
      })
      this.triggerEvent('closeGoodsSelectPop')
    },
    //处理当前选中的sku：
    dealCurrentSelectSku(sukData) {
      let arr = [];
      this.properties.goodsData.forEach((i, index) => {
        let obj = {
          attrName: i.attrName,
          list: [],
        }
        let strArr = i.attrValues.split(',');
        let newArr = []
        strArr.forEach((j, idx) => {
          let o = {
            name: j,
            isChoose: false,
          }

          if (idx == 0) {
            o.isChoose = true;
          }
          newArr.push(o)
        })
        obj.list = newArr;
        arr.push(obj)
      })
      this.setData({
        sukList: arr,
      })
      console.log("JJLog:看看==：" + JSON.stringify(this.data.sukList));
    },
    //切换规格：
    goodsSelectSkuAction(e) {
      // let item = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      let bigIndex = e.currentTarget.dataset.bigindex;
      console.log('JJLog:bigIndex：' + bigIndex)
      let aItem = this.data.sukList[bigIndex];
      console.log("JJLog:aItem:" + JSON.stringify(aItem));
      let aList = aItem.list;
      aList.forEach(i => {
        i.isChoose = false;
      })
      aList[index].isChoose = true;
      aItem.list = aList;
      let cItem = 'sukList[' + bigIndex + ']';
      this.setData({
        [cItem]: aItem,
      })

      console.log('JJLOg:变化后的是：' + JSON.stringify(this.data.sukList));
      let selectSuks = [];
      this.data.sukList.forEach(j => {
        let list = j.list;
        list.forEach(k => {
          if (k.isChoose) {
            selectSuks.push(k.name)
          }
        })
      })
      let selectSuk = selectSuks.join(',');

      this.data.skuList.forEach(m => {
        if (m.suk == selectSuk) {
          this.setData({
            selectSkuObj: m,
          })
        }
      })

      // this.setData({
      //   selectSkuObj: item,
      //   selectSkuIndex: index
      // })


    },
    //选择数量
    selectNumberChange(e) {
      this.setData({
        selectNumber: e.detail
      })
    },
    //加入购物车
    handlerShopCar() {
      if (!app.globalData.isLogin) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return;
      }
      if (this.properties.goodType == 'seckill') {
        wx.showToast({
          title: '秒杀商品暂不支持加入购物车',
          icon: "none"
        })
        return;
      }
      let requestBody = {
        productId: this.data.selectSkuObj.productId,
        productAttrUnique: this.data.selectSkuObj.id,
        isNew: false,
        cartNum: this.data.selectNumber
      }
      wx.showLoading();
      saveGoodToCart(requestBody).then(res => {
        wx.hideLoading();
        if (res.code == 200) {
          wx.showToast({
            title: '加入成功',
            icon: "none"
          })
          this.triggerEvent('addCartSuccess');
        }
      }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err || '加入购物车失败',
          icon: "none"
        })
        console.error("JJLog:saveGoodToCart", err);
      })

    },
    //立即购买
    handlerBuy() {
      if (!app.globalData.isLogin) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return;
      }
      let productInfo = this.properties.productInfo;
      if (this.properties.goodType == "seckill") {
        productInfo.id = productInfo.productId;
      }
      let reData = {
        skuObj: this.data.selectSkuObj,
        selectNumber: this.data.selectNumber,
        productInfo: productInfo
      }
      app.globalData.jiesuanInfo = reData;
      // this.closePageContainer();
      wx.navigateTo({
        url: '/featurePackage/pages/submitOrder/submitOrder?type=buyNow' + "&goodType=" + this.properties.goodType,
      })

    }
  }
})